package com.bamboowind.producer.topics;

import com.bamboowind.producer.util.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;

/**
 * 通配符模式:生产者
 *
 * @author cpw
 */
public class ProducerTopics {
    private final static String QUEUE_NAME1 = "rabbitmq-topicQueue1";
    private final static String QUEUE_NAME2 = "rabbitmq-topicQueue2";
    private final static String EXCHANGE_NAME = "rabbitmq-topicExchange";

    public static void main(String[] args) throws IOException {

        //3.创建连接Connection
        Connection connection = RabbitMqUtils.getConnection();

        //4.创建Channel
        Channel channel = connection.createChannel();


        /**
         * exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
         * 参数:
         *      1.exchange:交换机名称
         *      2.type:交换机类型
         *            DIRECT("direct"), 定向
         *            FANOUT("fanout"), 广播，发送消息到每一个与之绑定的队列
         *            TOPIC("topic"),   通配符的方式
         *            HEADERS("headers");参数匹配
         *      3.durable:是否持久化
         *      4.autoDelete:自动删除
         *      5.internal:内部使用，一般false
         *      6.arguments:参数
         * */

        //5.创建交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC, true, false, false, null);

        //6.创建队列
        channel.queueDeclare(QUEUE_NAME1, true, false, false, null);
        channel.queueDeclare(QUEUE_NAME2, true, false, false, null);

        /**
         * queueBind(String queue, String exchange, String routingKey, Map<String)
         * 参数:
         *      1.queue:队列名称
         *      2.exchange:交换机名称
         *      3.routingKey:路由键绑定规则
         *          如果交换机的类型为fanout，那么routingKey设置为""
         * */

        //7.绑定队列和交换机

        // routingKey: 系统的名称.日志的级别
        //需求：所有error级别的日志和order订单的信息都存入数据库;不管什么级别的信息都打印到控制台
        // #:代表多个单词 *:代表一个单词
        channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, "#.error");
        channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, "order.*");

        channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "*.*");
        //8.发送消息
        //String body = "cpw发送了一条信息，日志级别为info...";
        //String body = "cpw发送了一条信息，order.info...";
        String body = "cpw发送了一条信息，goods.info...";
        channel.basicPublish(EXCHANGE_NAME, "goods.info", null, body.getBytes());

        //9.释放资源
        RabbitMqUtils.closeConnectionAndChannel(connection, channel);
    }
}